package com.ks.interceptor;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

public class AuthInterceptor extends HandlerInterceptorAdapter {
    private final static Logger log = Logger.getLogger(AuthInterceptor.class);

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("UTF-8");
        String url = request.getRequestURI();

        if (url.indexOf("login") >= 0 || url.indexOf("logout") >= 0 || url.indexOf("proof") >= 0) {
            return true;
        }
        // 判断是否是已登录
        HttpSession session = request.getSession(false);
        if (null == session || null == session.getAttribute("userInfo")) {
            // 无session是未登录状态
            System.out.println("session出现问题！");
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath + "/sys/login");
            return false;
        } else {
            // 禁止缓存
            session.setMaxInactiveInterval(30 * 60);
            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragrma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.addHeader("x-frame-options", "SAMEORIGIN");
            response.addHeader("X-Content-Type-Options", "nosniff");
            response.addHeader("X-XSS-Protection", "1;mode=block");
            // 链接来源地址
            String referer = request.getHeader("referer");
            if (referer == null || !referer.contains(request.getServerName())) {
                return false;
            }
        }
        return true;
    }

    /**
     * 记录日志
     *
     * @param request
     * @param handler
     * @param ex
     */
    public void logger(HttpServletRequest request, Object handler, Exception ex) {
        StringBuffer msg = new StringBuffer();
        msg.append("异常拦截日志");
        msg.append("[uri＝").append(request.getRequestURI()).append("]");
        Enumeration<String> enumer = request.getParameterNames();
        while (enumer.hasMoreElements()) {
            String name = (String) enumer.nextElement();
            String[] values = request.getParameterValues(name);
            msg.append("[").append(name).append("=");
            if (values != null) {
                int i = 0;
                for (String value : values) {
                    i++;
                    msg.append(value);
                    if (i < values.length) {
                        msg.append("｜");
                    }

                }
            }
            msg.append("]");
        }
        log.error(msg, ex);
    }
}
